<template>
  <div class="login_container">
    <div class="login_box">
      <el-form ref="loginFormRef" :rules="loginFormRules" :model="loginForm" label-width="0px">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user-solid" v-model="loginForm.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" placeholder="请输入密码" v-model="loginForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button type="info" @click="handleResetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {loginRequest} from '../api/request'
export default {
  name: 'Login',
  data: function() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleResetForm() {
      this.$refs.loginFormRef.resetFields()
    },
    handleLogin() {
      this.$refs.loginFormRef.validate(val => {
        if (!val) return;
        loginRequest(this.loginForm).then(res => {
          if (res.meta.status !== 200) {
            this.$message.error('登录失败')
          } else {
            const { token } = res.data
            sessionStorage.setItem('token', token)
            this.$message.success('登录成功')
            this.$router.push('/home')
          }
        })
      })
    }
  }
}
</script>

<style lang='less' scoped>
  .login_container {
    background-color: #2b4b6b;
    height: 100%;
    .login_box {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 450px;
      height: 200px;
      border-radius: 3px;
      background-color: #fff;
      padding: 30px 20px;
    }
    .btns {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>